package me.stone.stanimeclient.core.ui.adapters.base

import android.view.View
import android.view.ViewGroup
import androidx.databinding.ViewDataBinding
import androidx.recyclerview.widget.AsyncDifferConfig
import androidx.recyclerview.widget.DiffUtil
import androidx.recyclerview.widget.ListAdapter
import androidx.recyclerview.widget.RecyclerView.ViewHolder
import me.stone.stanimeclient.core.ui.adapters.listener.OnItemClickListener
import me.stone.stanimeclient.core.ui.extensions.getPositionTag
import me.stone.stanimeclient.core.ui.extensions.setPositionTag
import java.util.concurrent.Executor

abstract class AbsViewDataBoundAdapter<T, V: ViewDataBinding>(
    backExecutor: Executor,
    diffCallback: DiffUtil.ItemCallback<T>
): ListAdapter<T, AbsViewDataBoundAdapter<T, V>.DataBoundHolder<V>>(
    AsyncDifferConfig.Builder(diffCallback)
        .setBackgroundThreadExecutor(backExecutor)
        .build()
), View.OnClickListener {

    inner class DataBoundHolder<V: ViewDataBinding>(
        val binding: V,
    ): ViewHolder(binding.root)

    override fun onCreateViewHolder(
        parent: ViewGroup,
        viewType: Int
    ): DataBoundHolder<V> {
        return DataBoundHolder(createDataBinding(parent))
    }

    override fun onBindViewHolder(
        holder: DataBoundHolder<V>,
        position: Int
    ) {
        holder.binding.root.setOnClickListener(this@AbsViewDataBoundAdapter)
        holder.binding.root.setPositionTag(position)
        bindData(holder.binding, getItem(position), position)
        holder.binding.executePendingBindings()
    }

    override fun onClick(v: View) {
        v.getPositionTag().takeIf { it != -1 }?.let {
            mListener?.onItemClicked(getItem(it))
        }
    }

    private var mListener: OnItemClickListener<T>? = null

    fun setOnItemClickListener(listener: OnItemClickListener<T>) {
        mListener = listener
    }

    abstract fun createDataBinding(parent: ViewGroup): V

    abstract fun bindData(binding: V, item: T, position: Int)

}